##parameters=form=None
from Products.KnowledgeEngine.AssessmentFilter import AssessmentFilter, decodeAssessmentFilterFromString
from Products.KnowledgeEngine.Utils.CallbackIterator import CallbackIterator
from Products.KnowledgeEngine.KERLProcessor import parseKERL, compileKERLtoEnglish

user = context.REQUEST.AUTHENTICATED_USER

if not form: form = context.REQUEST.form

assessmentStorageService = context.knowledgeengine_assessmentstorageservice
userProviderService = context.knowledgeengine_userproviderservice
keuser = userProviderService.getUser(context.REQUEST["AUTHENTICATED_USER"].getId())

# Check for a KERL statement passed from the form
# If KERL is passed, we use that to get a list of matching assessments, 
# completely overriding the SQL based search
kerl = form.get('kerl',None)
if kerl:
    
    models = context.portal_catalog(portal_type='Model')
    model = models[0].getObject()
    
    return compileKERLtoEnglish( parseKERL( kerl ), model )


mappings = context.demo_search_mapping()


# qstring is a function to `escape` a string to prevent SQL Injection attacks
qstring = assessmentStorageService.qstring

# Get the search.*:record values sent via the form
# i.e. If we pass search.name:record, then we can access it via search['name']
search = dict(form['search']) or {}

modelIdentities      = [qstring(identity) for identity in form.get('modelIdentities', [])]
repositoryIdentities = [qstring(identity) for identity in form.get('repositoryIdentities', [])]

joincount = 0 # Used to give each instance of the latestAnswers table a unique ID when we do an INNER JOIN

clauses = []

for mapping in mappings:
    
    english     = mapping.get('english',None)
    label       = mapping.get('label', None)
    searchIndex = mapping['idx']
    searchValue = search.get(searchIndex, None)
    
    if not (searchIndex and searchValue): continue # Skip this searchIndex if no value is specified
     
    searchType = mapping.get('searchType', 'equals')
    widget     = mapping.get('widget','auto')
    
    clause = "`%s` " % (english or label or searchIndex)
    
    if widget == 'MultiSelect':
        clause += 'is in %s ' % ','.join( [value for value in searchValue] )
        
    elif widget in ('Range','DateRange'):
        value_max = search.get( searchIndex + "_max", None )
        isInt     = mapping.get( 'valueType' ) == 'Integer'
        
        if value_max:
            clause += "is between '%s' and '%s'" % ( searchValue, value_max )
        else:
            clause += "is equal to '%s'" % qstring(searchValue, quote=(not isInt))
        
        
    elif searchType == 'like':
        clause += "contains the string '%s'" % searchValue
    else:
        clause += "is equal to '%s'" % searchValue
        
    clauses.append( clause )        


english = "Show all assessments"    
if clauses:
    english += " where "
    english += ' and '.join( clauses )


if modelIdentities:
  #sql += " AND search.modelIdentity in (" + ','.join(modelIdentities) + ") "
  pass

return english
                          

